var redis = require("redis");
var async = require('async');
var config = require('../config');
var logger = require('../logger');

var _client = null;

function log() {
    logger.log(arguments);
}

function connect(cb) {
    //创建redis客户端
    _client = redis.createClient(config.redisPort, config.redisHost);
    //连接错误处理
    _client.on("error", (err) => {
        if (err) {
            cb('redis connect err:' + err);
        }
    });
    _client.select(config.redisOrderDatabase, (err) => {
        if (err) {
            cb('redis select database:' + err);
        } else {
            cb(null);
        }
    })
}

function client() {
    return _client;
}

function addcartitem(user, fileid, func) {
    _client.sadd(user + config.allcarts, fileid, (err, response) => {
        func(err);
    });
}

function removecartitem(user, fileid, func) {
    _client.srem(user + config.allcarts, fileid, (err, response) => {
        func(err);
    });
}

function getallcarts(user, cb) {
    _client.smembers(user + config.allcarts, (err, response) => {
        cb(err, response);
    })
}

function createorder(user, info, func) {
    async.waterfall([
        (cb) => {
            _client.incr(user + '.MaxOrder', (err, response) => {
                cb(err, response);
            });
        },

        (order, cb) => {
            var content = JSON.stringify(info);
            _client.hset(user + config.allorders, order, content, (err, response) => {
                cb(err, order);
            });
        }
    ], (err, order) => {
        func(err, order);
    });
}

function removeorderitem(user, order, func) {
    _client.hdel(user + config.allorders, order, (err, response) => {
        func(err);
    });
}

function finishorder(user, orderid, func) {
    async.waterfall([
        (cb) => {
            _client.hget(user + config.allorders, orderid, (err, response) => {
                cb(err, response);
            });
        },
        (cb, content) => {
            var info = JSON.parse(content);
            info.state = 1;
            var s = JSON.stringify(info);
            _client.hset(user + config.allorders, orderid, s, (err, response) => {
                cb(err);
            })
        }
    ], (err) => {
        func(err);
    });
}

function getallorders(user, func) {
    _client.hgetall(user + config.allorders, (err, response) => {
        func(err, response);
    });
}

function getorder(user, order, func) {
    _client.hget(user + config.allorders, order, (err, response) => {
        if (err) {
            func(err);
        } else {
            var info = JSON.parse(response);
            info.order = order;
            func(null, info);
        }
    })
}

module.exports = {
    connect,
    client,
    addcartitem,
    getallcarts,
    removecartitem,
    createorder,
    getallorders,
    getorder,
    finishorder,
    removeorderitem,
}